package com.wumz.netty.tomcat.bio;


import com.wumz.netty.tomcat.bio.http.MyRequest;
import com.wumz.netty.tomcat.bio.http.MyResponse;
import com.wumz.netty.tomcat.bio.http.MyServlet;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * Tomcat启动类
 * Created by wumz on 2021/2/4 15:07
 */
public class MyTomcat {

    private int port = 8080;

    private ServerSocket server;

    private Properties webxml = new Properties();

    private Map<String, MyServlet> servletMapping = new HashMap<String, MyServlet>();

    public static void main(String[] args) {

        new MyTomcat().start();
    }

    //Tomcat启动入口
    private void start() {
        //1、加载web-bio.properties配置文件
        init();

        //2、启动服务端Socket长连接，等待用户请求
        try {
            server = new ServerSocket(this.port);
            System.out.println("My Tomcat 已启动，监听端口是："+this.port);
            while (true){
                Socket accept = server.accept();

                //3、获得请求信息，解析HTTP协议内容
                process(accept);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    private void process(Socket client) {
        try {
            InputStream is = client.getInputStream();
            OutputStream os = client.getOutputStream();

            MyRequest request = new MyRequest(is);
            MyResponse response = new MyResponse(os);

            String url = request.getUrl();

            if (servletMapping.containsKey(url)){
                servletMapping.get(url).service(request, response);
            } else {
                response.write("404 - Not Found!!");
            }

            os.flush();
            os.close();
            is.close();
            client.close();

        }catch (Exception e){
            e.printStackTrace();
        }

    }

    private void init() {
        try {
            String WEB_INFO = this.getClass().getResource("/").getPath();
            FileInputStream fis = new FileInputStream(WEB_INFO + "web-bio.properties");
            webxml.load(fis);
            for (Object k : webxml.keySet()){
                String key = k.toString();
                if (key.endsWith(".url")){
                    //将 servlet.xxx.url 的 .url 替换，只剩下 servlet.xxx当成  servletName
                    String servletName = key.replaceAll("\\.url$", "");
                    String url = webxml.getProperty(key);

                    //拿到Servlet全类名
                    String clazzName = webxml.getProperty(servletName + ".className");

                    //反射创建Servlet实例
                    MyServlet obj = (MyServlet) Class.forName(clazzName).newInstance();

                    //建立URL和Servlet的映射关系
                    servletMapping.put(url, obj);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
